package dbStruct;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import dbStruct.Connector.RelationType;
import dbStruct.Node.NodeType;

public class Connectors {
	private static Connectors instance;
	private HashMap<String, Connector> connectors;
	
	public static Connectors getInstance()	{
		if(instance==null) instance=new Connectors();
		return instance;
	}
	
	public Connectors()	{
		super();
		connectors=new HashMap<String, Connector>();
	}
	
	public void add(Connector connector){
		String name = connector.getSource().getName() + 
					  "." + 
					  connector.getDestination().getName();
		connectors.put(name, connector);
	}
	
	public Connector remove(String name){
		Connector connector = connectors.get(name);
		connectors.remove(name);
		return connector;
	}
	
	public Connector get(String name)	{
		return connectors.get(name);
	}
	
	public boolean exists(Connector connector){
		return connectors.containsValue(connector);
	}
	
	public boolean exists(String name){
		return connectors.containsKey(name);
	}
	
	public void clear(){
		connectors.clear();
	}
	
	public Vector<Node> getColumns(String tableName)
	{
		Vector<Node> columns = new Vector<Node>();
		Iterator<Connector> it = connectors.values().iterator();
		System.out.println("*** Ricerca colonne per la tabella " + tableName);
		while(it.hasNext())
		{
			Connector conn = it.next();
			System.out.println("*** conn: " + conn.getDestination().getName());
			if(conn.getDestination().getType()==NodeType.COLUMN)
			{
				Column col = (Column) conn.getDestination();
				if(col.getTableName().equalsIgnoreCase(tableName))
					columns.add(col);
			}
		}
		return columns;
	}
	
	public Vector<Connector> getRelations(String tableName)
	{
		Vector<Connector> relations = new Vector<Connector>();
		Iterator<Connector> it = connectors.values().iterator();
		while(it.hasNext())
		{
			Connector conn = it.next();
			if(conn.getSource().getName().equals(tableName))
			{	//Prelevo tutte le relazioni con la tabella specificata
				if(conn.getRelationType()==RelationType.RELATION)
					relations.add(conn);
			}
		}
		return relations;
	}
}
